package team.damo.admin.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import team.damo.admin.dao.UserServiceDAO;
import team.damo.admin.model.User;
import team.damo.admin.service.UserService;
import team.damo.common.enums.ResponseCode;
import team.damo.common.utils.DateUtils;
import team.damo.common.utils.MD5Utils;
import team.damo.common.utils.ResponseEntity;

import java.util.Date;

/**
 * @Author: ZhangHeng
 * @Description: TODO
 * @DateTime: 2024/3/12 10:48
 **/
@Service
@Slf4j
public class UserviceImpl implements UserService {
    @Autowired
    private UserServiceDAO userServiceDAO;

    @Override
    public ResponseEntity register(User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        if (username == null || username.isEmpty()){
            log.debug("{}用户名不能为空",user);
            return ResponseEntity.error()
                    .message("用户名不能为空");
        }
        if (password == null || password.isEmpty()) {
            log.debug("{}密码不能为空",user);
            return ResponseEntity.error()
                    .message("密码不能为空");
        }
        // 查询数据库中当前用户名是否存在
        boolean userIsExist = userServiceDAO.isExist(username);
        if (userIsExist) {
            log.debug("{}当前用户已存在",user);
            return ResponseEntity.error()
                    .message("当前用户已存在");
        }
        // 校验通过,创建新用户
        User newUser = new User();
        String newPassWord = MD5Utils.string2MD5(password);
        newUser.setUsername(username);
        newUser.setPassword(newPassWord);
        newUser.setCreateTime(DateUtils.parseDateToStr(new Date(),DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS));
        userServiceDAO.addUser(newUser);
        return ResponseEntity.ok();
    }

    @Override
    public ResponseEntity login(User user) {
        String username = user.getUsername();
        String password = user.getPassword();
        if (username == null || username.isEmpty()){
            log.debug("{}用户名不能为空",user);
            return ResponseEntity.error()
                    .message("用户名不能为空");
        }
        if (password == null || password.isEmpty()) {
            log.debug("{}密码不能为空",user);
            return ResponseEntity.error()
                    .message("密码不能为空");
        }
        // 查询当前登录用户名信息
        User oldUser = userServiceDAO.selectByUsername(username);
        if (!MD5Utils.passwordIsTrue(password,oldUser.getPassword())) {
            // 登录失败
            log.debug("用户{}登录失败",username);
            return ResponseEntity.error()
                    .message("用户名密码错误");
        }
        log.info("用户{}登录成功",oldUser);
        return ResponseEntity.ok();
    }
}
